package com.youmans.userservice.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.youmans.common_utils.config.Result;
import com.youmans.common_utils.exception.DfsException;
import com.youmans.common_utils.handler.JwtUtils;
import com.youmans.common_utils.vo.LoginVo;
import com.youmans.common_utils.vo.RegisterVo;
import com.youmans.userservice.service.YoumansUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

//@CrossOrigin
@RestController
@RequestMapping("/admin/system/user")
public class UserSystemController {
    @Autowired
    private YoumansUserService youmansUserService ;

//    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo){
        String token ;
        Map<String,Object> map;
        try {
             token = youmansUserService.login(loginVo);
            map = new HashMap<>();
            map.put("token",token);
            return Result.ok(map);
        }catch (DfsException e){
           // e.printStackTrace();
           return Result.fail().message(e.getMsg());
        }
    }
    @ApiOperation("注册用户")
    @PostMapping("register")
    public Result register(@RequestBody RegisterVo registerVo){
        try{
        boolean b = youmansUserService.register(registerVo);
        return b?Result.ok():Result.fail().message("系统错误，请重试");
        }catch (DfsException e){
            return Result.fail().message(e.getMsg());
        }
    }
    @GetMapping("info")
    public Result info(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        try {
            String memberId = JwtUtils.getMemberIdByJwtToken(request);
            LoginVo loginInfoVo = youmansUserService.getLoginInfo(memberId);
            map.put("roles","admin");
            map.put("introduction","I am a super administrator");
            map.put("avatar",loginInfoVo.getAvatar());
            map.put("name",loginInfoVo.getUsername());
            map.put("userId",memberId);

            /*
            获取ip原
            String ip =getResult(request);
            System.out.println("ip:"+ip);
            map.put("ip",ip);
                */

            return Result.ok(map);
//            return R.ok().data("item", loginInfoVo);
        }catch (Exception e){
            e.printStackTrace();
            throw new DfsException(20001,"error");
        }
//        {"code":20000,
// "data":
// {"roles":["admin"],
// "introduction":"I am a super administrator","
// avatar":"https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
// "name":"Super Admin"}}


        //return Result.ok(map);
    }

    private String getResult(HttpServletRequest request) {
        String ip;
// 有的user可能使用代理，为处理用户使用代理的情况，使用x-forwarded-for
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        } else {
            ip = request.getHeader("x-forwarded-for");
        }
        if ("127.0.0.1".equals(ip)) {
            try {
// 获取本机真正的ip地址
                ip = InetAddress.getLocalHost().getHostAddress();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        System.err.println(ip);
        return ip;

        /**

         获取请求ip
         @param request
         @return
         */
//        public static String getIP(HttpServletRequest request){
//            String ip = request.getRemoteAddr();
//            String headerIP = request.getHeader("x-real-ip");
//            if(headerIP == null || "".equals(headerIP) || "null".equals(headerIP)){
//                headerIP = request.getHeader("x-forwarded-for");
//            }
//            System.out.println("headerIP:"+headerIP);
//            if(headerIP !=null && !"".equals(headerIP) && !"null".equals(headerIP)){
//                ip = headerIP;
//            }
//            return ip;
//        }



//
//        String ip = request.getHeader("x-forwarded-for");
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("HTTP_CLIENT_IP");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//        }
//        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getRemoteAddr();
//        }
//        return ip;





//          String[] ADDR_HEADER = { "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
//                "X-Real-IP" };
//         String NUKNOWN = "unknown";
//        String addr = null;
//        if (request instanceof HttpServletRequest) {
//            HttpServletRequest hsr = (HttpServletRequest) request;
//            for (String header : ADDR_HEADER) {
//                if (StringUtils.isBlank(addr) || NUKNOWN.equalsIgnoreCase(addr)) {
//                    addr = hsr.getHeader(header);
//                } else {
//                    break;
//                }
//            }
//        }
//        if (StringUtils.isBlank(addr) || NUKNOWN.equalsIgnoreCase(addr)) {
//            addr = request.getRemoteAddr();
//        } else {
//            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按','分割
//            if (addr != null) {
//                int i = addr.indexOf(",");
//                if (i > 0) {
//                    addr = addr.substring(0, i);
//                }
//            }
//
//        }
//        return addr;






        //            获取ip
//        String ip = request.getRemoteAddr();
//        System.out.println("ip:"+ip);
//        String headerIP = request.getHeader("x-real-ip");
//        if(headerIP == null || "".equals(headerIP) || "null".equals(headerIP)){
//            headerIP = request.getHeader("x-forwarded-for");
//        }
//        System.out.println("headerIP:"+headerIP);
//        if(headerIP !=null && !"".equals(headerIP) && !"null".equals(headerIP)){
//            ip = headerIP;
//        }
//        return ip;


    }

    @RequestMapping("logout")
//    @GetMapping
    public Result logout(HttpSession session){
        session.invalidate();
        return Result.ok();
    }

}
